<template>
  <view class="content">
    <view class="top">
      <view class="mydevice">我的设备</view>
    </view>
    <!-- 横向滚动 -->
    <view class="hand">
      <scroll-view scroll-x="true" style="white-space: nowrap;">
        <view class="RoomAll">
          <view
            v-for="(room, index) in roomList"
            :key="index"
            class="RoomList"
            @click="handleRoom(index, room.roomId)"
          >
            <view class="room-switch">
              <image
                v-bind:src="`../../static/images/room/room${room.roomPic}.png` "
                class="room-icon"
              ></image>
            </view>
            <view :class="['room-name', { 'blue-text': clickedIndex === index }]">
              {{ room.roomName }}
            </view>
          </view>
        </view>
      </scroll-view>
    </view>
    <view class="List">
      <text class="List-device">设备</text>
      <image
        class="plus-icon"
        src="../../static/images/room/plus.png"
        mode="aspectFit"
        @click="handleMore"
      ></image>
    </view>

    <!-- 设备列表 -->
    <view class="DeviceAll">
      <!-- click事件点击跳转/传递数据 -->
      <view
        v-for="(device, index) in filteredDeviceList"
        :key="index"
        class="DeviceListc"
        @click="goToDeviceDetail(device)"
        :class="{ 'DeviceList-on': device.status === 'true' }"
        @longpress="handleLongPress(device)"
      >
        <view class="device-switch">
         <!-- <image
            v-bind:src="`../../static/images/device/${device.deviceTypes}.png`"
            class="device-icon"
          ></image> -->
		  <image :src="getDeviceIcon(device.deviceTypes)" class="device-icon"></image>
        </view>
        <view class="device-name">{{ device.deviceName }}</view>
        <view class="device-types">{{ device.deviceTypes }}</view>
        <!-- 滑动按钮 -->
        <switch
          :checked="device.status === 'true'"
          @change="toggleSwitch(device, index)"
          class="check"
        />
      </view>
    </view>

    <modal
      :visible="modalVisible"
      @close="modalVisible = false"
      @confirm="handleModalConfirm"
    >
      <view>{{ modalMessage }}</view>
    </modal>
  </view>
</template>

<script>
  import {
    listDevice,
    getDevice,
    addDevice,
    updateDevice,
    delDevice,
  } from "@/api/device/device.js";

  import { getRoom } from "@/api/room/room.js";
  import Modal from "@/components/Modal.vue";

  export default {
    components: {
      Modal,
    },
    data() {
      return {
        deviceList: [],
        roomList: "",
        clickedIndex: 0, //记录被点击房间的索引
        selectedRoomId: null, // 记录被点击房间的ID
        indicatorDots: false,
        newDevice: {
          status: "",
        },
        modalVisible: false,
        modalMessage: "",
        allLightsOn: false, // 初始状态
        deleteMode: false, // 是否为删除模式
        currentDeviceId: null, // 记录当前设备的唯一ID
      };
    },
    computed: {
      filteredDeviceList() {
        return this.deviceList.filter(
          (device) => device.roomId === this.selectedRoomId
        );
      },
    },
    methods: {
      getDeviceList() {
        getDevice()
          .then((res) => {
            this.deviceList = res.rows;
            console.log(this.deviceList);
          })
          .catch((error) => {
            console.error("Error fetching device:", error);
          });
      },
	  getDeviceIcon(types) {
	  	// 返回房间图标的路径
	  	switch (types) {
	  		case '灯泡':
	  			return '../../static/images/device/dengpao.png';
	  		case '时钟':
	  			return '../../static/images/device/shizhong.png';
	  		case '床':
	  			return '../../static/images/device/chuang.png';
	  		case '风扇':
	  			return '../../static/images/device/fengshan.png';
	  		case '冰箱':
	  			return '../../static/images/device/bingxiang.png';
	  		case '马桶':
	  			return '../../static/images/device/matong.png';
	  		case '游戏手柄':
	  			return '../../static/images/device/shoubing.png';
	  		case '台灯':
	  			return '../../static/images/device/taideng.png';
	  		case '手机':
	  			return '../../static/images/device/shouji.png';
	  		case '电视':
	  			return '../../static/images/device/dianshi.png';
	  		case '锅':
	  			return '../../static/images/device/guo.png';
	  		case '插座':
	  			return '../../static/images/device/chazuo.png';
	  		case '插头':
	  			return '../../static/images/device/chatou.png';
	  		case '空调':
	  			return '../../static/images/device/kongtiao.png';
	  		default:
	  			return '';
	  	}
	  },
      // 长按删除
      handleModalConfirm() {
        if (this.deleteMode && this.currentDeviceId !== null) {
          delDevice(this.currentDeviceId)
            .then(() => {
              console.log("成功删除");
              this.getDeviceList();
              this.modalVisible = false;
            })
            .catch((error) => {
              console.error("删除失败:", error);
            });
        } else {
          console.log("取消删除");
          this.modalVisible = false;
        }
      },
      getRoomList() {
        getRoom().then((res) => {
          this.roomList = res.rows;
          if (this.clickedIndex != 0) {
            this.selectedRoomId = this.roomList[this.clickedIndex].roomId;
          } else {
            this.selectedRoomId = this.roomList[0].roomId;
          }
        });
      },
      handleLongPress(device) {
        this.currentDeviceId = device.id;
        this.modalMessage = "是否删除该设备？";
        this.deleteMode = true;
        this.modalVisible = true;
      },
      handleRoom(index, roomId) {
        this.clickedIndex = index;
        this.selectedRoomId = roomId;
      },
      handleMore() {
        uni.navigateTo({
          url: "/pages/device/newdevice",
        });
      },
      toggleSwitch(device, index) {
        event.stopPropagation(); // 阻止事件冒泡
        device.status = device.status === "true" ? "false" : "true";
        this.update(device);
      },
      update(device) {
        updateDevice(device)
          .then(() => {})
          .catch((error) => {
            console.error("失败:", error.response ? error.response.data : error);
            uni.showToast({
              title: "失败，请重试",
              icon: "none",
            });
          });
      },
      goToDeviceDetail(device) {
        uni.navigateTo({
          url: `/pages/device/device?device=${encodeURIComponent(
            JSON.stringify(device)
          )}`,
        });
      },
    },
    onShow() {
      this.getRoomList();
      this.getDeviceList();
    },
  };
</script>

<style lang="scss">
	page {
		background-color: #f9f9f9;
		 
	}
	.content {
		//margin-top: 34px;
	}
	.hand {
		height: 205rpx;
		width: 100%;
		padding-right: 22rpx;
		padding-top: 120rpx;
	}

	.RoomAll {
		height: 230rpx;
		width: 100%;
		display: flex;
		padding: 20rpx;
	}

	.RoomList {
		margin: 10rpx;
		padding-left: 16rpx;
		// margin-right: 23px;
		align-items: center;

	}

	.RoomList:first-child {
		// margin-left: 2px;
	}

	.room-icon {
		display: inline-block;
		height: 118rpx;
		width: 120rpx;
		border-radius: 15%;
		padding-right: 5rpx;
		object-fit: contain;
		/* 保持图片比例 */
	}

	.room-name {
		margin-top: 15rpx;
		text-align: center;
		font-size: 29rpx;
		margin-right: 10rpx;
		color: #969db0;
	}

	.mydevice {
		font-size: 38rpx;
		color: #4e6490;
		font-weight: bold;
	}

	.top {
		display: flex;
		justify-content: center;
		/* 子元素在容器中居中对齐 */
		align-items: center;
		/* 垂直方向居中 */
		height: 92rpx;
		background-color:white;
		padding: 4rpx;
		position: fixed;
		/* 将状态栏固定在最上方 */
		
		/* 从顶部开始定位 */
		left: 0;
		/* 从左侧开始定位 */
		width: 100%;
		/* 宽度100%，充满整个屏幕 */
		z-index: 9999;
		/* 确保状态栏位于其他内容上方 */
		border-bottom: 1.5px solid #f0f0f0;
		/* 下方灰色边框线 */
	}

	.blue-text {
		color: blue;
	}

	.List {
		padding: 37rpx;
		margin-top: 120rpx;
		display: flex;
		align-items: center;
		/* 垂直方向居中 */
		justify-content: space-between;
		/* 子元素在容器两端 */
	}

	.List-device {
		font-size: 52rpx;
		color: #4e6490;
		font-weight: bold;
		float: left;
		margin-left: 20rpx;
	}

	.plus-icon {
		width: 68rpx;
		height: 68rpx;
		object-fit: contain;
		margin-left: 96rpx;
	}

	// .more {
	// 	color: #654bff;
	// 	float: right;
	// 	font-size: 18px;
	// }

	.DeviceAll {
		display: flex;
		flex-wrap: wrap;
		justify-content: space-between;
		padding: 35rpx;
		padding-top: 3rpx;

		/* 调整间距 */
	}

	.DeviceListc {
		display: block;
		margin: auto;
		background-color: white;
		padding: 42rpx;

		margin: 23rpx auto;
		border-radius: 25rpx;
		/* 圆角边框 */
		border: 1px #ced3df;
		/* 设置外边框 */
		box-shadow: 0 2px 3px rgba(0, 0, 0, 0.1);
		/* 阴影效果 */
		height: 360rpx;
		width: calc(50% - 20rpx);
		/* 每行两个元素，减去边距 */
		box-sizing: border-box;
		// z-index: 1;
		/* 包括内边距和边框在内计算宽度 */
	}

	.DeviceList-on {
		background-color: rgba(105, 105, 255, 0.19);
	}

	.DeviceListc:nth-child(2n+1) {
		margin-left: 0;
		/* 确保每行的第一个元素靠左 */
	}

	.DeviceListc:nth-child(2n) {
		margin-right: 0;
		/* 确保每行的第二个元素靠右 */
	}

	.device-name {
		font-size: 18px;
		color: #4e6490;
		font-weight: bold;
		padding-top: 41rpx;
	}

	.device-types {
		font-size: 13px;
		color: #808080;
		padding-top: 22rpx;
		padding-bottom: 22rpx;
		padding-left: 4rpx;
	}

	.device-switch {
		display: flex;
		justify-content: space-between;
		padding-left: 4rpx;
	}

	.device-icon {
		height: 80rpx;
		width: 80rpx;
		border-radius: 10%;
	}

	.swiper-list {
		padding-left: 1rpx;
	}

	.custom-switch {
		width: 50rpx;
		height: 25rpx;
		background-color: #808080;
		/* 默认灰色 */
		border-radius: 25px;
		position: relative;
		cursor: pointer;
		transition: background-color 0.3s;

	}

	.switch-on {
		background-color: #00b900;
		/* 开启时绿色 */
	}

	.switch-off {
		background-color: #987db9;
		/* 开启时绿色 */
	}

	.switch-circle {
		width: 23px;
		height: 23px;
		background-color: white;
		border-radius: 50%;
		position: absolute;
		top: 1px;
		left: 1px;
		transition: left 0.3s;

	}

	.circle-on {
		left: 26px;
		/* 圆点移动到右边 */
	}
</style>